import { HashService } from '@app/hash';
import { PrismaService } from '@app/prisma';
import { ClassesEntity } from '@app/prisma/classes.entity/classes.entity';
import { UseGuards } from '@nestjs/common';
import { Args, Int, Mutation, Query, Resolver } from '@nestjs/graphql';
import { GqlAuthPowerGuard, AccountPower } from 'src/auth/auth.guard';

@Resolver()
export class ClassesResolver {
    constructor(
        private readonly prisma: PrismaService,
        private readonly hashService: HashService
    ) { }

    @Mutation(() => [ClassesEntity])
    async getClassesByTeacher(
        @Args("id", { type: () => Int }) id: number
    ) {
        const teacher = await this.prisma.teacher.findUnique({
            where: {
                id
            },
            include: {
                TeacherOnClasses: {
                    include: {
                        classes: true
                    }
                }
            }
        })
        return teacher.TeacherOnClasses.map(e => e.classes)
    }

    @Query(() => ClassesEntity)
    getClassesById(
        @Args("id", { type: () => Int }) id: number
    ) {
        return this.prisma.classes.findUniqueOrThrow({
            where: {
                id
            },
            include: {
                User: {
                    include: {
                        profile: true
                    }
                },
                TeacherOnClasses: {
                    include: {
                        teacher: true
                    }
                }
            }
        })
    }

    @Mutation(() => ClassesEntity)
    @UseGuards(new GqlAuthPowerGuard(AccountPower))
    async updClasses(
        @Args("name") name: string,
        @Args("id", { type: () => Int }) id: number,
        @Args("scienceId", { type: () => Int }) scienceId: number
    ) {
        return this.prisma.classes.update({
            where: { id },
            data: {
                scienceId,
                name
            }
        }).catch((err) => {
            console.log("updClasses", err)
            return err;
        })
    }

    @Mutation(() => ClassesEntity)
    @UseGuards(new GqlAuthPowerGuard(AccountPower))
    delClasses(
        @Args("id") id: number
    ) {
        return this.prisma.classes.delete({ where: { id } })
    }

    @Mutation(() => ClassesEntity)
    @UseGuards(new GqlAuthPowerGuard(AccountPower))
    addClasses(
        @Args("name") name: string,
        @Args("scienceId", { type: () => Int, nullable: true }) scienceId: number
    ) {
        return this.prisma.classes.create({
            data: {
                name,
                scienceId
            }
        })
    }
}
